package com.example.wasaimovie.Advicer;

import com.example.wasaimovie.Annotation.DisableBaseResponse;
import com.example.wasaimovie.Model.support.ResponseResult;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 对全局的返回数据进行统一处理
 */
@RestControllerAdvice("com.example.wasaimovie.Controller")
public class GlobalResponseAdvicer implements ResponseBodyAdvice<Object> {
    // 判断是否需要进行加工
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        // 有DisableBaseResponse注解代表不进行封装
        return !(methodParameter.hasMethodAnnotation(DisableBaseResponse.class));
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (o == null){
            // 数据为空，返回空构造产生的数据
            return new ResponseResult<>();
        }
        return new ResponseResult<>(o);
    }
}
